from urllib import request,parse
import json,time,random,hashlib

def fanyi(keyword):
    # 有道翻译的url
    url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

    try:
        # 获取salt和sign
        u = 'fanyideskweb'
        c = 'ebSeFb%=XZ%T[KZ)c(sy!'

        salt = str(int(time.time() * 1000) + random.randint(1, 10))
        sign = hashlib.md5((u + keyword + salt + c).encode('utf-8')).hexdigest()

        # 定义请求的参数，并编码转换
        data = {
            'i': keyword,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': salt,
            'sign': sign,
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTIME',
            'typoResult': 'false',
        }
        data = parse.urlencode(data)

        # 设置headers的头信息
        headers={
            'Accept': 'application/json, text/javascript, */*; q = 0.01',
            'Accept-Encoding': 'deflate',
            'Accept-Language': 'zh-CN, zh;q=0.9,en;q=0.8',
            'Connection': 'keep-alive',
            'Content-Length': len(data),
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Cookie':'OUTFOX_SEARCH_USER_ID=-1269649655@10.168.8.63;JSESSIONID=aaaXuFE-XP8tY727k9wzw;DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|;JSESSIONID=abc8hqiRAEK2L_m4k9wzw;OUTFOX_SEARCH_USER_ID_NCOO=723317251.1363933;___rl__test__cookies=1539081253864',
            'Host':'fanyi.youdao.com',
            'Origin':'http://fanyi.youdao.com',
            'Referer':'http://fanyi.youdao.com/',
            'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/69.0.3497.100Safari/537.36',
            'X-Requested-With':'XMLHttpRequest',
        }

        # 发送请求，爬取信息
        req = request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
        res = request.urlopen(req)

        # 解析结果
        str_json = res.read().decode("utf-8")
        myjson = json.loads(str_json)
        info = myjson['translateResult'][0][0]['tgt']
        print(info)
    except Exception as e:
        print(e)

if __name__=='__main__':
    while True:
        keyword = input("请输入要翻译的词(输入q回车即为退出)：")
        if keyword == 'q':
            break
        fanyi(keyword)